import { defineStore } from 'pinia';
import { Session } from '/@/utils/storage';
import { useLoginApi } from '/@/api/login/index';
import { useUserApi } from '/@/api/user/index';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		loginUserInfo: {
			token: '',
			userInfo: {
				id: 0,
				nickName: '',
				avatar: '',
				authBtnList: [],
			},
		}
	}),
	actions: {
		async setUserInfos(data: any) {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.loginUserInfo = Session.get('userInfo');
			} else {
				const userInfos = <LoginUserInfo>await this.getApiUserInfo(data);
				this.loginUserInfo = userInfos;
				Session.set('userInfo', userInfos);
				Session.set('token', userInfos.token)
			}
		},
		// 模拟接口数据
		// https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
		async getApiUserInfo(data: any) : Promise<any> {
			return useLoginApi().signIn(data);
		},
		async setLoginUserInfo(){
			const userInfo = <LoginUserInfo>await this.getLoginUserInfo()
			this.loginUserInfo.userInfo = userInfo.userInfo
			Session.set('userInfo', this.loginUserInfo);
		},
		async getLoginUserInfo(): Promise<any> {
			return useUserApi().getLoginUserInfo();
		},
	},
});
